<template>
  <div class="scheduling-view">
    <div class="page-title">排班设置</div>

    <!-- 筛选和操作区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20" class="filter-row">
        <el-col :span="6" :xs="24" :sm="12">
          <el-date-picker
              v-model="selectedMonth"
              type="month"
              format="yyyy-MM-dd"
              value-format="YYYY-MM-DD"
              placeholder="选择月份"
              @change="handleMonthChange"
              style="width: 100%"
          />
        </el-col>
        <el-col :span="4" :xs="8" :sm="6">
          <el-button type="primary" @click="handleToday" class="w-full">今日</el-button>
        </el-col>
        <el-col :span="4" :xs="8" :sm="6">
          <el-button @click="handlePreviousMonth" class="w-full">上月</el-button>
        </el-col>
        <el-col :span="4" :xs="8" :sm="6">
          <el-button @click="handleNextMonth" class="w-full">下月</el-button>
        </el-col>
        <el-col :span="6" :xs="24" :sm="12" class="operation-col">
          <el-button @click="showBatchScheduleDialog = true">批量设置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 日历视图 -->
    <el-card class="calendar-card">
      <div class="calendar-header">
        <div class="weekday">周日</div>
        <div class="weekday">周一</div>
        <div class="weekday">周二</div>
        <div class="weekday">周三</div>
        <div class="weekday">周四</div>
        <div class="weekday">周五</div>
        <div class="weekday">周六</div>
      </div>

      <div class="calendar-body">
        <div
            v-for="(week, weekIndex) in calendarData"
            :key="weekIndex"
            class="calendar-week"
        >
          <div
              v-for="(day, dayIndex) in week"
              :key="dayIndex"
              :class="['calendar-day', {
              'other-month': day.otherMonth,
              'today': day.isToday,
              'has-schedule': day.schedules && day.schedules.length > 0
            }]"
          >
            <div class="day-number">{{ day.day }}</div>

            <div class="schedule-container">
              <div
                  v-for="(schedule, sIndex) in day.schedules"
                  :key="sIndex"
                  class="schedule-item"
                  :class="`schedule-${schedule.shift}`"
                  @click="handleViewSchedule(day, schedule)"
              >
                <div class="schedule-shift">
                  {{ schedule.shift === 'morning' ? '上午' :
                    schedule.shift === 'afternoon' ? '下午' : '晚上' }}
                </div>
                <div class="schedule-quota">
                  号源: {{ schedule.usedQuota }}/{{ schedule.totalQuota }}
                </div>
              </div>
            </div>

            <el-button
                size="mini"
                type="text"
                class="add-schedule-btn"
                @click.stop="handleAddSchedule(day)"
                :disabled="day.otherMonth"
            >
              + 新增
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑排班对话框 -->
    <el-dialog
        v-model="showAddScheduleDialog"
        :title="currentSchedule.id ? '编辑排班' : '新增排班'"
        :width="500"
    >
      <el-form ref="scheduleForm" :model="currentSchedule" label-width="100px">
        <el-form-item label="日期：" required>
          <el-date-picker
              v-model="currentSchedule.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="班次：" required>
          <el-radio-group v-model="currentSchedule.shift" @change="chnageRadio">
            <el-radio label="morning">上午</el-radio>
            <el-radio label="afternoon">下午</el-radio>
            <el-radio label="evening">晚上</el-radio>
          </el-radio-group>
        </el-form-item>



        <el-form-item label="开始时间：" required>
          <el-input
              v-model="currentSchedule.startTimeDisplay"
              placeholder="开始时间"
              readonly
          />
        </el-form-item>

        <el-form-item label="结束时间：" required>
          <el-input
              v-model="currentSchedule.endTimeDisplay"
              placeholder="结束时间"
              readonly
          />
        </el-form-item>

        <el-form-item label="总号源数：" required>
          <el-input
              v-model.number="currentSchedule.totalQuota"
              min="1"
              max="100"
              placeholder="请输入号源数量"
          />
        </el-form-item>

        <el-form-item label="挂号费：" required>
          <el-input
              v-model.number="currentSchedule.fee"
              min="0"
              placeholder="请输入挂号费用"
          />
          <template #append>元</template>
        </el-form-item>

        <el-form-item label="科室：" required>
          <el-select
              v-model="selectedDeptId"
              placeholder="请选择科室"
              @change="handleDeptChange"
              style="width: 100%"
          >
            <template v-for="dept in departments" :key="dept.dept_id">
              <!-- 第一级科室不能选择，只作为分组显示 -->
              <el-option-group :label="dept.name">
                <el-option
                    v-for="child in dept.children"
                    :key="child.dept_id"
                    :label="child.name"
                    :value="child.dept_id"
                />
              </el-option-group>
            </template>
          </el-select>
        </el-form-item>

        <el-form-item label="医生：" required>
          <el-select
              v-model="currentSchedule.doctorId"
              placeholder="请先选择科室"
              style="width: 100%"
              :disabled="!selectedDeptId"
          >
            <el-option
                v-for="doctor in doctors"
                :key="doctor.doctor_id"
                :label="`${doctor.name} ${doctor.title}`"
                :value="doctor.doctor_id"
            >
              <div class="doctor-option">
                <img
                    :src="doctor.avatar"
                    :alt="doctor.name"
                    class="doctor-avatar"
                >
                <div class="doctor-info">
                  <div>{{ doctor.name }} {{ doctor.title }}</div>
                  <div class="doctor-specialty">{{ doctor.specialty }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>


      </el-form>

      <template #footer>
        <el-button @click="showAddScheduleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveSchedule">保存</el-button>
      </template>
    </el-dialog>

    <!-- 批量设置排班对话框 -->
    <el-dialog
        v-model="showBatchScheduleDialog"
        title="批量设置排班"
        :width="600"
    >
      <el-form ref="batchForm" :model="batchSchedule" label-width="120px">
        <el-form-item label="日期范围：" required>
          <el-date-picker
              v-model="batchSchedule.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="重复周期：" required>
          <el-radio-group v-model="batchSchedule.period">
            <el-radio label="daily">每天</el-radio>
            <el-radio label="weekly">每周</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="重复星期：" required v-if="batchSchedule.period === 'weekly'">
          <el-checkbox-group v-model="batchSchedule.weekdays">
            <el-checkbox label="1">周一</el-checkbox>
            <el-checkbox label="2">周二</el-checkbox>
            <el-checkbox label="3">周三</el-checkbox>
            <el-checkbox label="4">周四</el-checkbox>
            <el-checkbox label="5">周五</el-checkbox>
            <el-checkbox label="6">周六</el-checkbox>
            <el-checkbox label="0">周日</el-checkbox>
          </el-checkbox-group>
        </el-form-item>


        <el-collapse>
          <el-collapse-item title="上午设置" v-if="batchSchedule.shifts.includes('morning')">
            <el-form-item label="时间段：">
              <el-input
                  v-model="batchSchedule.morningTimeDisplay"
                  readonly
              />
            </el-form-item>
            <el-form-item label="总号源数：">
              <el-input
                  v-model.number="batchSchedule.morningQuota"
                  min="1"
                  max="100"
              />
            </el-form-item>
          </el-collapse-item>

          <el-collapse-item title="下午设置" v-if="batchSchedule.shifts.includes('afternoon')">
            <el-form-item label="时间段：">
              <el-input
                  v-model="batchSchedule.afternoonTimeDisplay"
                  readonly
              />
            </el-form-item>
            <el-form-item label="总号源数：">
              <el-input
                  v-model.number="batchSchedule.afternoonQuota"
                  min="1"
                  max="100"
              />
            </el-form-item>
          </el-collapse-item>

          <el-collapse-item title="晚上设置" v-if="batchSchedule.shifts.includes('evening')">
            <el-form-item label="时间段：">
              <el-input
                  v-model="batchSchedule.eveningTimeDisplay"
                  readonly
              />
            </el-form-item>
            <el-form-item label="总号源数：">
              <el-input
                  v-model.number="batchSchedule.eveningQuota"
                  min="1"
                  max="100"
              />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>

        <el-form-item label="班次：" required>
          <el-checkbox-group v-model="batchSchedule.shifts">
            <el-checkbox label="morning">上午</el-checkbox>
            <el-checkbox label="afternoon">下午</el-checkbox>
            <el-checkbox label="evening">晚上</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="挂号费：" required>
          <el-input
              v-model.number="batchSchedule.fee"
              min="0"
              placeholder="请输入挂号费用"
          />
          <template #append>元</template>
        </el-form-item>
        <el-form-item label="科室：" required>
          <el-select
              v-model="batchSchedule.deptId"
              placeholder="请选择科室"
              @change="handleBatchDeptChange"
              style="width: 100%"
          >
            <template v-for="dept in departments" :key="dept.dept_id">
              <el-option-group :label="dept.name">
                <el-option
                    v-for="child in dept.children"
                    :key="child.dept_id"
                    :label="child.name"
                    :value="child.dept_id"
                />
              </el-option-group>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="医生：" required>
          <el-select
              v-model="batchSchedule.doctorId"
              placeholder="请先选择科室"
              style="width: 100%"
              :disabled="!batchSchedule.deptId"
          >
            <el-option
                v-for="doctor in doctors"
                :key="doctor.doctor_id"
                :label="`${doctor.name} ${doctor.title}`"
                :value="doctor.doctor_id"
            >
              <div class="doctor-option">
                <img
                    :src="doctor.avatar"
                    :alt="doctor.name"
                    class="doctor-avatar"
                >
                <div class="doctor-info">
                  <div>{{ doctor.name }} {{ doctor.title }}</div>
                  <div class="doctor-specialty">{{ doctor.specialty }}</div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="showBatchScheduleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveBatchSchedule">确认设置</el-button>
      </template>
    </el-dialog>

    <!-- 排班详情对话框 -->
    <el-dialog
        v-model="showScheduleDetailDialog"
        title="排班详情"
        :width="500"
    >
      <el-card>
        <div class="detail-item">
          <span class="detail-label">日期：</span>
          <span class="detail-value">{{ formatDate(currentScheduleDetail.date) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">星期：</span>
          <span class="detail-value">{{ getWeekday(currentScheduleDetail.date) }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">班次：</span>
          <span class="detail-value">
            {{ currentScheduleDetail.shift === 'morning' ? '上午' :
              currentScheduleDetail.shift === 'afternoon' ? '下午' : '晚上' }}
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">时间：</span>
          <span class="detail-value">
            {{ formatTime(currentScheduleDetail.startTime) }} - {{ formatTime(currentScheduleDetail.endTime) }}
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">号源情况：</span>
          <span class="detail-value">
            已使用：{{ currentScheduleDetail.usedQuota }} / 总号源：{{ currentScheduleDetail.totalQuota }}
          </span>
        </div>
        <div class="detail-item">
          <span class="detail-label">挂号费：</span>
          <span class="detail-value">{{ currentScheduleDetail.fee }} 元</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">诊室：</span>
          <span class="detail-value">{{ currentScheduleDetail.room || '-' }}</span>
        </div>

      </el-card>

      <template #footer>
        <el-button @click="showScheduleDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="handleEditSchedule">编辑</el-button>
        <el-button
            type="primary"
            text-color="#fff"
            background="#ff4d4f"
            @click="handleDeleteSchedule"
        >
          删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted ,getCurrentInstance} from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
const {proxy} = getCurrentInstance();

// 状态管理
const selectedMonth = ref(new Date());
const calendarData = ref([]);
const totalDaysInMonth = ref(0);
const firstDayOfMonth = ref(0);

// 对话框状态
const showAddScheduleDialog = ref(false);
const showBatchScheduleDialog = ref(false);
const showScheduleDetailDialog = ref(false);
const currentSchedule = ref({});
const currentScheduleDetail = ref({});

const currentSelectedDay = ref();

const chnageRadio = (shift) => {
  // 确保有日期
  if (!currentSchedule.value.visit_date) {
    ElMessage.warning('请先选择日期');
    return;
  }


  // 创建日期对象
  const date = new Date(currentSchedule.value.visit_date);

  // 根据班次设置时间
  switch(shift) {
    case 'morning':
      date.setHours(8, 0, 0);
      currentSchedule.value.start_time = date;
      currentSchedule.value.startTimeDisplay = '08:00:00';

      date.setHours(12, 0, 0);
      currentSchedule.value.end_time = date;
      currentSchedule.value.endTimeDisplay = '12:00:00';
      break;

    case 'afternoon':
      date.setHours(12, 0, 0);
      currentSchedule.value.start_time = date;
      currentSchedule.value.startTimeDisplay = '12:00:00';

      date.setHours(18, 0, 0);
      currentSchedule.value.end_time = date;
      currentSchedule.value.endTimeDisplay = '18:00:00';
      break;

    case 'evening':
      date.setHours(18, 0, 0);
      currentSchedule.value.start_time = date;
      currentSchedule.value.startTimeDisplay = '18:00:00';

      date.setHours(24, 0, 0);
      currentSchedule.value.end_time = date;
      currentSchedule.value.endTimeDisplay = '24:00:00';
      break;
  }
};

// 批量排班数据
const batchSchedule = reactive({
  dateRange: [],
  period: 'weekly',
  weekdays: ['1', '2', '3', '4', '5'], // 默认周一至周五
  shifts: ['morning', 'afternoon'],
  morningQuota: 20,
  afternoonQuota: 20,
  eveningQuota: 10,
  fee: 50,
  deptId: '', // 新增科室ID
  doctorId: '', // 新增医生ID
  morningTimeDisplay: '08:00 - 12:00',
  afternoonTimeDisplay: '12:00 - 18:00',
  eveningTimeDisplay: '18:00 - 24:00'
});


// 批量排班科室选择变化时触发
const handleBatchDeptChange = (deptId) => {
  batchSchedule.deptId = deptId;
  batchSchedule.doctorId = ''; // 清空当前选择的医生
  fetchDoctorsByDept(deptId); // 获取该科室下的医生
};


// 初始化日历数据
const initCalendar = () => {
  const year = selectedMonth.value.getFullYear();
  const month = selectedMonth.value.getMonth();

  // 获取当月天数
  totalDaysInMonth.value = new Date(year, month + 1, 0).getDate();

  // 获取当月第一天是星期几 (0-6, 0是星期日)
  firstDayOfMonth.value = new Date(year, month, 1).getDay();

  // 生成日历数据
  const calendar = [];
  let dayCount = 1;
  let nextMonthDay = 1;

  // 上个月的最后几天
  const prevMonth = month === 0 ? 11 : month - 1;
  const prevMonthYear = month === 0 ? year - 1 : year;
  const prevMonthDays = new Date(prevMonthYear, prevMonth + 1, 0).getDate();

  for (let i = 0; i < 6; i++) { // 最多6行
    const week = [];
    for (let j = 0; j < 7; j++) { // 7天/周
      if (i === 0 && j < firstDayOfMonth.value) {
        // 上个月的日期
        week.push({
          day: prevMonthDays - firstDayOfMonth.value + j + 1,
          date: new Date(prevMonthYear, prevMonth, prevMonthDays - firstDayOfMonth.value + j + 1),
          otherMonth: true,
          isToday: false,
          schedules: []
        });
      } else if (dayCount > totalDaysInMonth.value) {
        // 下个月的日期
        week.push({
          day: nextMonthDay++,
          date: new Date(year, month + 1, nextMonthDay - 1),
          otherMonth: true,
          isToday: false,
          schedules: []
        });
      } else {
        // 当月的日期
        const currentDate = new Date(year, month, dayCount);
        const isToday = currentDate.toDateString() === new Date().toDateString();

        week.push({
          day: dayCount++,
          date: currentDate,
          otherMonth: false,
          isToday: isToday,
          schedules: getSchedulesForDate(currentDate)
        });
      }
    }
    calendar.push(week);

    // 如果已经显示完当月所有日期，跳出循环
    if (dayCount > totalDaysInMonth.value && nextMonthDay > 7) break;
  }

  calendarData.value = calendar;
};

// 模拟排班数据
const scheduleData = ref([
  {
    id: 1,
    date: new Date(2023, 4, 15), // 5月15日
    shift: 'morning',
    startTime: '08:00',
    endTime: '12:00',
    totalQuota: 20,
    usedQuota: 8,
    fee: 50,
  }
]);

// 获取指定日期的排班
const getSchedulesForDate = (date) => {
  return scheduleData.value.filter(item => {
    return item.date.toDateString() === date.toDateString();
  });
};

// 处理月份变更
const handleMonthChange = () => {
  initCalendar();
};

// 切换到今天
const handleToday = () => {
  selectedMonth.value = new Date();
  initCalendar();
};

// 切换到上月
const handlePreviousMonth = () => {
  selectedMonth.value = new Date(
      selectedMonth.value.getFullYear(),
      selectedMonth.value.getMonth() - 1,
      1
  );
  initCalendar();
};

// 切换到下月
const handleNextMonth = () => {
  selectedMonth.value = new Date(
      selectedMonth.value.getFullYear(),
      selectedMonth.value.getMonth() + 1,
      1
  );
  initCalendar();
};

// 添加排班
const handleAddSchedule = (day) => {
  currentSelectedDay.value = day;

  currentSchedule.value = {
    visit_date: day.date,
    time_slot: 'morning',
    start_time: null,
    end_time: null,
    startTimeDisplay: '',
    endTimeDisplay: '',
    total_quota: 100,
    price: 50.99,
    doctor_id: '',
    dept_id: null,
  };

  showAddScheduleDialog.value = true;
};




// 查看排班详情
const handleViewSchedule = (day, schedule) => {
  // 查找完整的排班信息
  currentScheduleDetail.value = { ...scheduleData.value.find(item =>
        item.id === schedule.id && item.date.toDateString() === day.date.toDateString()
    )};
  showScheduleDetailDialog.value = true;
};

// 编辑排班
const handleEditSchedule = () => {
  currentSchedule.value = { ...currentScheduleDetail.value };
  showScheduleDetailDialog.value = false;
  showAddScheduleDialog.value = true;
};

// 删除排班
const handleDeleteSchedule = () => {
  // 模拟API请求
  axios.delete(`/xxx`)
      .then(response => {
        console.log('排班删除成功', response.data);
        // 从数据中移除
        const index = scheduleData.value.findIndex(item => item.id === currentScheduleDetail.value.id);
        if (index !== -1) {
          scheduleData.value.splice(index, 1);
        }
        showScheduleDetailDialog.value = false;
        initCalendar(); // 重新初始化日历
      })
      .catch(error => {
        console.error('排班删除失败', error);
      });
};

// 保存单条排班
const saveSchedule = () => {
  if (currentSchedule.value.id) {
    axios.put(`/xxx`, currentSchedule.value)
        .then(response => {
          console.log('排班更新成功', response.data);
          const index = scheduleData.value.findIndex(item => item.id === currentSchedule.value.id);
          if (index !== -1) {
            scheduleData.value[index] = { ...currentSchedule.value };
          }
          showAddScheduleDialog.value = false;
          initCalendar();
        })
        .catch(error => {
          console.error('排班更新失败', error);
        });
  } else {
    currentSchedule.value.start_time = formatDateTime(currentSchedule.value.start_time)
    currentSchedule.value.end_time = formatDateTime(currentSchedule.value.end_time)
    currentSchedule.value.visit_date = formatDateTime(currentSchedule.value.visit_date)
    // 添加新排班
    const now = new Date();
    const newSchedule = {
      visit_date: currentSchedule.value.visit_date, // 使用 currentSchedule 中的日期
      time_slot: currentSchedule.value.time_slot === 'morning' ? 1 :
          currentSchedule.value.time_slot === 'afternoon' ? 2 : 3,
      start_time: currentSchedule.value.start_time,
      end_time: currentSchedule.value.end_time,
      total_quota: currentSchedule.value.total_quota,
      remaining_quota: currentSchedule.value.total_quota, // 剩余号源初始等于总号源
      price: currentSchedule.value.fee,
      doctor_id: currentSchedule.value.doctorId,
      dept_id: currentSchedule.value.dept_id,
      status: 0,
      create_time: undefined,
      update_time: undefined,
    };
    //http://localhost:8089/api/v1/schedule/insertOne
    proxy.$axios.post('/api/v1/schedule/insertOne',newSchedule)
        .then(response => {
          console.log('排班添加成功', response.data);
          scheduleData.value.push(newSchedule);
          showAddScheduleDialog.value = false;
          initCalendar();
        })
        .catch(error => {
          console.error('排班添加失败', error);
        });
  }
};

// 保存批量排班
const saveBatchSchedule = async () => {
  if (!batchSchedule.deptId || !batchSchedule.doctorId) {
    ElMessage.error('请选择科室和医生');
    return;
  }

  if (!batchSchedule.dateRange || batchSchedule.dateRange.length !== 2) {
    ElMessage.error('请选择日期范围');
    return;
  }

  if (batchSchedule.shifts.length === 0) {
    ElMessage.error('请至少选择一个班次');
    return;
  }

  try {
    // 准备请求参数
    const params = {
      doctorId: batchSchedule.doctorId,
      deptId: batchSchedule.deptId,
      price: batchSchedule.fee,
      dateRange: [
        formatDate(batchSchedule.dateRange[0]),
        formatDate(batchSchedule.dateRange[1])
      ],
      period: batchSchedule.period,
      weekdays: batchSchedule.weekdays,
      shifts: batchSchedule.shifts,
      morningQuota: batchSchedule.morningQuota,
      afternoonQuota: batchSchedule.afternoonQuota,
      eveningQuota: batchSchedule.eveningQuota,
      morningStartTime: '08:00',
      morningEndTime: '12:00',
      afternoonStartTime: '12:00',
      afternoonEndTime: '18:00',
      eveningStartTime: '18:00',
      eveningEndTime: '24:00'
    };

    const response = await proxy.$axios.post('/api/v1/schedule/batch', params);
    console.log(response)
    if (response.data.success) {
      ElMessage.success(response.data.message);
      showBatchScheduleDialog.value = false;
      initCalendar(); // 刷新日历
    } else {
      ElMessage.error(response.data.message || '批量排班设置失败');
    }
  } catch (error) {
    console.error('批量排班设置失败', error);
    ElMessage.error('批量排班设置失败');
  }
};





// 格式化日期显示
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
};


const formatDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`;
};


// 格式化时间显示
// const formatTime = (time) => {
//   return time || '';
// };

const formatTime = (time) => {
  if (!time) return '';
  if (typeof time === 'string') return time;

  const hours = time.getHours().toString().padStart(2, '0');
  const minutes = time.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
};

// 获取星期几
const getWeekday = (date) => {
  if (!date) return '';
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  return weekdays[new Date(date).getDay()];
};


const departments = ref([]);
const doctors = ref([]);
const selectedDeptId = ref('');

// 获取科室列表数据
const fetchDepartments = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:8080/api/v1/departments');
    if (response.data.code === 0) {
      departments.value = response.data.data;
    } else {
      ElMessage.error('获取科室列表失败');
    }
  } catch (error) {
    console.error('获取科室列表出错:', error);
    ElMessage.error('获取科室列表时发生错误');
  }
};

// 根据科室ID获取医生列表
const fetchDoctorsByDept = async (deptId) => {
  if (!deptId) {
    doctors.value = [];
    return;
  }

  try {
    const response = await axios.get(`http://127.0.0.1:8080/api/v1/department/${deptId}/doctor`);
    if (response.data.code === 0) {
      doctors.value = response.data.data;
    } else {
      ElMessage.error('获取医生列表失败');
      doctors.value = [];
    }
  } catch (error) {
    console.error('获取医生列表出错:', error);
    ElMessage.error('获取医生列表时发生错误');
    doctors.value = [];
  }
};

// 科室选择变化时触发
const handleDeptChange = (deptId) => {
  selectedDeptId.value = deptId;
  currentSchedule.value.dept_id = deptId;
  // 清空当前选择的医生
  currentSchedule.value.doctorId = '';
  // 获取该科室下的医生
  fetchDoctorsByDept(deptId);
};

// 在初始化时获取科室列表
onMounted(() => {
  initCalendar();
  fetchDepartments(); // 新增这一行
});










</script>

<style scoped>
.scheduling-view {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #1e293b;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.calendar-card {
  padding: 15px;
}

.calendar-header {
  display: flex;
  margin-bottom: 10px;
}

.weekday {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  background-color: #f1f5f9;
  font-weight: 500;
  border-radius: 4px 4px 0 0;
}

.calendar-body {
  display: flex;
  flex-direction: column;
}

.calendar-week {
  display: flex;
  flex: 1;
}

.calendar-day {
  flex: 1;
  min-height: 120px;
  border: 1px solid #e2e8f0;
  padding: 5px;
  position: relative;
}

.calendar-day.other-month {
  background-color: #f8fafc;
  opacity: 0.6;
}

.calendar-day.today {
  background-color: #eff6ff;
}

.day-number {
  font-weight: 500;
  margin-bottom: 5px;
  padding: 2px 0;
}

.schedule-item {
  padding: 3px 5px;
  margin-bottom: 3px;
  border-radius: 3px;
  font-size: 12px;
  cursor: pointer;
}

.schedule-morning {
  background-color: #dbeafe;
  border-left: 3px solid #3b82f6;
}

.schedule-afternoon {
  background-color: #dcfce7;
  border-left: 3px solid #22c55e;
}

.schedule-evening {
  background-color: #fef3c7;
  border-left: 3px solid #f59e0b;
}

.schedule-shift {
  font-weight: 500;
}

.schedule-quota {
  font-size: 11px;
  color: #64748b;
}

.add-schedule-btn {
  position: absolute;
  bottom: 5px;
  right: 5px;
  padding: 0;
  font-size: 12px;
  color: #3b82f6;
}

.calendar-day.has-schedule .add-schedule-btn {
  display: none;
}

/* 详情样式 */
.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-label {
  color: #64748b;
  width: 80px;
  flex-shrink: 0;
}

.detail-value {
  flex-grow: 1;
  font-weight: 500;
}

.full-width {
  width: 100%;
}



.doctor-option {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.doctor-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.doctor-info {
  line-height: 1.4;
}

.doctor-specialty {
  font-size: 12px;
  color: #666;
}


</style>
